<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>创建链表</title>
</head>
<body>

</body>
<script>
    class Node {
        constructor(element) {
            this.element = element
            this.next = null
        }
    }
    class LinkedList {
        constructor() {
            this.head = null
            this.length = 0
        }

        append(element) {
            const node = new Node(element)
            if (this.head === null) {
                this.head = node
            } else {
                let current = this.head;
                while (current.next) {
                    current = current.next
                }
                current.next = node
            }
            this.length++
        }

        remove(pos) {
            if (pos > -1 && pos < this.length) {
                let current = this.head,
                    prev,
                    index = 0;
                //如果是移除第一个元素
                if (pos === 0) {
                    this.head = current.next
                } else {
                    /*
                    *    遍历链表直到需要删除位置
                    *
                    * */
                    while (index < pos) {
                        prev = current
                        current = current.next
                        index++
                    }
                    /*
                    *  删除元素操作 将删除元素上一个元素的next指向当前元素的下一个元素
                    * */
                    prev.next = current.next

                    this.length--

                    return current.element
                }
            } else {
                return null
            }
        }

        insert(element, pos) {
            const node = new Node(element);
            if (pos > -1 && pos <= this.length) {
                let current = this.head,
                    prev,
                    index = 0;
                if (pos === 0) {
                    this.head = node
                    this.head.next = current
                } else {
                    while (index++ < pos) {
                        prev = current
                        current = current.next
                    }
                    prev.next = node
                    node.next = current
                }
                this.length++
            } else {
                return false
            }
        }

    }


    const link = new LinkedList()
    link.append('a')
    link.append('b')
    link.append('c')
    console.log(link)

</script>
</html>